package com.workstudy.wstudy.service.impl;

import com.workstudy.common.core.domain.entity.SysRole;
import com.workstudy.common.core.domain.entity.SysUser;
import com.workstudy.common.utils.DateUtils;
import com.workstudy.common.utils.StringUtils;
import com.workstudy.system.service.ISysRoleService;
import com.workstudy.system.service.ISysUserService;
import com.workstudy.wstudy.domain.*;
import com.workstudy.wstudy.mapper.WstCreditUserMapper;
import com.workstudy.wstudy.mapper.WstPostExamineMapper;
import com.workstudy.wstudy.mapper.WstPostUserMapper;
import com.workstudy.wstudy.service.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.management.relation.Role;
import java.sql.PreparedStatement;
import java.util.Date;
import java.util.List;

@Service
public class WstProcessServiceImpl implements IWstProcessService {

    @Autowired
    private IWstPostService postService;

    @Autowired
    private IWstApplyService applyService;

    @Autowired
    private WebSocketServiceImpl webSocketService;

    @Autowired
    private IWstRecordService recordService;

    @Autowired
    private IWstMessageService messageService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private WstCreditServiceImpl creditService;

    @Autowired
    private WstPostUserMapper postUserMapper;

    @Autowired
    private WstPostExamineMapper postExamineMapper;

    @Override
    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    public int submitPost(WstPost post) {
        String exmineUserId = post.getParams().get("exmineUserId").toString();
        SysUser loginUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        //如果没有指定审核人审核，那就直接发布
        if (!exmineUserId.equals("0")){
            WstPostExamine postExamine1 = postExamineMapper.selectWstPostExamineById(post.getPostId());
            if (postExamine1 == null){
                WstPostExamine postExamine = new WstPostExamine(post.getPostId(),loginUser.getUserId(),new Long(exmineUserId));
                postExamineMapper.insertWstPostExamine(postExamine);
            }
            post.setStatus(Constants.ApprovalStatus.PENDING.toString());
            post.setUpdateTime(DateUtils.getNowDate());
            return postService.updateWstPost(post);
        }else{
            post.setPostStatus(Constants.PostStatus.IN_HANDING.toString());
            post.setStatus(Constants.PostStatus.IN_HANDING.toString());
            post.setUpdateTime(DateUtils.getNowDate());
            return postService.updateWstPost(post);
        }
    }

    @Override
    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    public synchronized int examinePost(WstRecord record) {
        SysUser loginUser = (SysUser)SecurityUtils.getSubject().getPrincipal();
        WstPost post = new WstPost();
        record.setUserName(loginUser.getUserName());
        record.setCreateUserId(loginUser.getUserId());
        record.setCreateBy(loginUser.getUserName());
        recordService.insertWstRecord(record);
        if ("AGREE".equals(record.getStatus())){
            postExamineMapper.deleteWstPostExamineById(record.getPostId());
            post.setUpdateUserId(loginUser.getUserId());
            post.setUpdateTime(DateUtils.getNowDate());
            post.setUpdateBy(loginUser.getUserName());
            post.setPostId(record.getPostId());
            post.setPostStatus(Constants.PostStatus.IN_HANDING.toString());
            post.setStatus(Constants.PostStatus.IN_HANDING.toString());
            post.setUpdateTime(DateUtils.getNowDate());
            return postService.updateWstPost(post);
        } else if ("DISAGREE".equals(record.getStatus())){
            post.setUpdateUserId(loginUser.getUserId());
            post.setUpdateTime(DateUtils.getNowDate());
            post.setUpdateBy(loginUser.getUserName());
            post.setPostId(record.getPostId());
            post.setStatus(Constants.ApprovalStatus.APPROVAL_FAILED.toString());
            post.setUpdateTime(DateUtils.getNowDate());
            return postService.updateWstPost(post);
        }
        return 0;
    }

    @Override
    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    public synchronized int apply(WstApply apply) {
        SysUser loginUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        apply.setStudentId(loginUser.getUserId());
        Boolean status =this.applyService.studentPost(apply);
        if (status){
            apply.setCreateUserId(loginUser.getUserId());
            apply.setCreateBy(loginUser.getUserName());
            apply.setCreateTime(DateUtils.getNowDate());
            apply.setStudentId(loginUser.getUserId());
            apply.setApplyStatus(Constants.ApplyStatus.IN_HANDING.toString());
            apply.setStatus(Constants.ApprovalStatus.WAITING_FOR_APPROVAL.toString());
            return applyService.insertWstApply(apply);
        }
        return 0;
    }

    @Override
    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    public int examineApply(WstRecord record) {
        SysUser user = (SysUser)SecurityUtils.getSubject().getPrincipal();
        record.setCreateBy(user.getUserName());
        record.setCreateUserId(user.getUserId());
        record.setCreateTime(DateUtils.getNowDate());
        Long applyId = new Long(record.getParams().get("applyId").toString());
        WstApply apply = applyService.selectWstApplyById(applyId);
        apply.setUpdateBy(user.getUserName());
        apply.setUpdateTime(DateUtils.getNowDate());
        if ("AGREE".equals(record.getStatus())){
            //学生是否符合条件 有无在职
            Boolean flag =  this.examineStatus(record.getUserId(),record.getPostId());
            if (flag){
                //条件符合
                apply.setStatus(Constants.ApprovalStatus.APPROVAL_SUCCESS.toString());
            } else{
                //条件不符合
                apply.setApplyStatus(Constants.ApplyStatus.FINISHED.toString());
                apply.setStatus(Constants.ApprovalStatus.APPROVAL_FAILED.toString());
            }
        }else if("DISAGREE".equals(record.getStatus())){
            apply.setApplyStatus(Constants.ApplyStatus.FINISHED.toString());
            apply.setStatus(Constants.ApprovalStatus.APPROVAL_FAILED.toString());
        }
        applyService.updateWstApply(apply);
        return recordService.insertWstRecord(record);
    }

    @Override
    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    public int offer(WstApply apply) {
        WstPost paramsPost = postService.selectWstPostById(apply.getPostId());
        WstApply apply0 = applyService.selectWstApplyById(apply.getApplyId());
        SysUser user =(SysUser)SecurityUtils.getSubject().getPrincipal();
        if ("AGREE".equals(apply.getParams().get("status"))){
            paramsPost.setUpdateTime(DateUtils.getNowDate());
            paramsPost.setActuals(paramsPost.getActuals()==null?1:paramsPost.getActuals()+1);
            postService.updateWstPost(paramsPost);
            apply.setApplyStatus(Constants.ApplyStatus.FINISHED.toString());
            apply.setStatus(Constants.ApprovalStatus.AGREE.toString());
            apply.setUpdateTime(DateUtils.getNowDate());
            applyService.updateWstApply(apply);
            WstPostUser paramsPostUser = new WstPostUser();
            paramsPostUser.setPostId(apply.getPostId());
            paramsPostUser.setUserId(user.getUserId());
            paramsPostUser.setStatus("ON");
            return postUserMapper.insertWstPostUser(paramsPostUser);
        }else if("DISAGREE".equals(apply.getParams().get("status"))){
            //不同意的扣分
            creditService.minusByRevoke(apply0.getStudentId());
            apply.setApplyStatus(Constants.ApplyStatus.FINISHED.toString());
            apply.setStatus(Constants.ApprovalStatus.DISAGREE.toString());
            apply.setUpdateTime(DateUtils.getNowDate());
            return applyService.updateWstApply(apply);
        }
        return 0;
    }

    @Override
    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    public int finished(WstPost post) {
        SysUser user = (SysUser)SecurityUtils.getSubject().getPrincipal();
        post.setUpdateTime(DateUtils.getNowDate());
        post.setUpdateBy(user.getUserName());
        post.setUpdateUserId(user.getUserId());
        return postService.updateWstPost(post);
    }

    @Override
    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    public int dismissal(WstPostUser postUser) {
        return postUserMapper.updateWstPostUser(postUser);
    }

    /**
     * 查看post 与 人员 是否符合条件
     * @param userId
     * @param postId
     * @return
     */
    public boolean examineStatus(Long userId,Long postId){
        WstPostUser postUser = new WstPostUser();
        postUser.setPostId(postId);
        postUser.setUserId(userId);
        List<WstPostUser> list = postUserMapper.selectWstPostUserList(postUser);
        for (WstPostUser p: list) {
            if (p.getStatus().equals("ON")){
                return false;
            }
        }
        return  true;
    }
}
